package com.bird.component.exception

import com.bird.component.lang.common.exception.ServiceException
import com.bird.component.lang.common.response.JSONResponse
import com.bird.component.lang.util.log
import org.springframework.core.annotation.Order
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice

@RestControllerAdvice
@Order(-1)
class GlobalExceptionHandler {

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(ServiceException::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun businessException(e: ServiceException): JSONResponse<Any> {
        log.error("业务异常：{}", e.message, e)
        val jsonResponse: JSONResponse<Any> =
            JSONResponse(
                msg = e.message,
                time = System.currentTimeMillis(),
                status = e.status,
                result = e.data
            )
        return jsonResponse
    }

    /**
     * 拦截optional.get()为空时的运行时异常
     */
    @ExceptionHandler(NoSuchElementException::class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    fun notResource(e: NoSuchElementException): JSONResponse<Any> {
        log.error("运行时异常 {}", e.localizedMessage, e)
        var internalServerError = com.bird.component.lang.common.exception.StatusInfo.INTERNAL_SERVER_ERROR
        return JSONResponse(
            msg = internalServerError.message(),
            time = System.currentTimeMillis(),
            status = internalServerError.status(),
            result = internalServerError.data
        )
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun unknownException(e: RuntimeException): JSONResponse<Any> {
        log.info("未知异常：{}", e.message, e)
        var internalServerError = com.bird.component.lang.common.exception.StatusInfo.INTERNAL_SERVER_ERROR
        return JSONResponse(
            msg = internalServerError.message(),
            time = System.currentTimeMillis(),
            status = internalServerError.status(),
            result = internalServerError.data
        )
    }
    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(Exception::class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    fun exception(e: Exception): JSONResponse<Any> {
        log.info("未知异常：{}", e.message, e)
        var internalServerError = com.bird.component.lang.common.exception.StatusInfo.INTERNAL_SERVER_ERROR
        return JSONResponse(
            msg = internalServerError.message(),
            time = System.currentTimeMillis(),
            status = internalServerError.status(),
            result = internalServerError.data
        )
    }
}